// packageA/pages/cashService/admin/addPerson/addPerson.js
import Dialog from '../../../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const { request } = require('../../../../../utils/request');
const { encryptSM2, decryptSM4 } = require('../../../../../utils/sm-crypto');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    staffName: '',
    idNum: '',  //202309整改，字段含义改为账号
    phoneNum: '',
    enableFlag: 'Y',
    remark: '',
    staffNo: '',
    station: '',
    loginType:'',
    captchaData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    this.setData({
      station: wx.getStorageSync('userInfo').stationName,
      loginType: wx.getStorageSync('userInfo').loginType
    })
    if (options.data) {
      wx.setNavigationBarTitle({
        title: '编辑人员',
      })
      let tempData = JSON.parse(options.data)
      this.setData({
        id: tempData.id,
        staffName: tempData.staffName,
        idNum: tempData.idNum,
        phoneNum: tempData.phoneNum,
        enableFlag: tempData.enableFlag,
        staffNo: tempData.staffNo,
        remark: tempData.remark,
      })
      this.getDetails(tempData.id)
    } else {
      wx.setNavigationBarTitle({
        title: '新增人员',
      })
    }
    this.fetchCaptcha()
  },
  onChange({ detail }) {
    // 需要手动对 enableFlag 状态进行更新
    if (detail) {
      this.setData({ enableFlag: 'Y' });
    } else {
      this.setData({ enableFlag: 'N' });
    }
  },
    // 获取人员信息详情
    getDetails(id) {
      const key = '4f39f20ec1fd479fa6dc3fd2d353d47d'
      let timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      request('/smsk/wechat/staff/details', 'GET',{id:id, timestamp: timestamp}).then(res => {
        if (res.data.code == 0) {
          // 脱敏修改以方便客户
          this.setData({
            staffName: decryptSM4(res.data.data.staffName, key),
            idNum: decryptSM4(res.data.data.idNum, key),
            phoneNum: decryptSM4(res.data.data.phoneNum, key)
          })
        } else {
          console.log(res)
        }
      })
    },
  fetchCaptcha() {
    request('/smsk/wechat/auth/captchaw150h30', 'GET').then(res => {
      this.setData({
        captchaData: res.data.data
      })
    })
  },
  submit() {
    if (!this.validForm()) {
      return false
    }
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    let queryData = {
      id: this.data.id,
      staffName: this.data.staffName,
      idNum: this.data.idNum,
      phoneNum: this.data.phoneNum,
      post: '操作员',
      remark: this.data.remark,
      staffNo: this.data.staffNo,
      enableFlag: this.data.enableFlag,
      staffType:2, // 1公司 2三方
      timestamp: timestamp,
      captchaId: this.data.captchaData.captchaId
    }
    if (this.data.id) {
      //202309，更新需脱敏
      // if (queryData.idNum.length == 18) {
      //   let prefix = queryData.idNum.substring(0,6)
      //   let suffix = queryData.idNum.substring(14)
      //   queryData.idNum = prefix + "********" + suffix
      // }
      // let staffNameLength = queryData.staffName.length
      // if (staffNameLength == 2) queryData.staffName = queryData.staffName.substring(0,1) + "*"
      // else if (staffNameLength > 2) {
      //   let mid = ""
      //   for(let i=0; i<staffNameLength-2; i++) {
      //     mid.concat("*")
      //   }
      //   queryData.staffName = queryData.staffName.substring(0,1) + mid + queryData.staffName.substring(staffNameLength-1)
      // }
      // let prefix = queryData.phoneNum.substring(0,3)
      // let suffix = queryData.phoneNum.substring(7)
      // queryData.phoneNum = prefix + "****" + suffix
      //202309，加密
      queryData.idNum = encryptSM2(queryData.idNum, this.data.captchaData.publicKey);
      queryData.staffName = encryptSM2(queryData.staffName, this.data.captchaData.publicKey)
      queryData.phoneNum = encryptSM2(queryData.phoneNum, this.data.captchaData.publicKey)
      request('/smsk/wechat/staff/update', 'POST', queryData).then(res => {
        console.log(res.data)
        if (res.data.code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1500);
        } else {
          Dialog.alert({
            message: res.data.message,
            confirmButtonText: '确认',
            confirmButtonColor: '#00A7DC',
            customStyle: 'border-radius: 5px;',
            closeOnClickOverlay: true
          }).then(res => {

          })
        }
      })
    } else {
      //202309，加密
      queryData.idNum = encryptSM2(queryData.idNum, this.data.captchaData.publicKey);
      queryData.staffName = encryptSM2(queryData.staffName, this.data.captchaData.publicKey)
      queryData.phoneNum = encryptSM2(queryData.phoneNum, this.data.captchaData.publicKey)
      request('/smsk/wechat/staff/add', 'POST', queryData).then(res => {
        console.log(res.data)
        if (res.data.code == 0) {
          wx.showToast({
            title: '创建成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1500);
        } else {
          Dialog.alert({
            message: res.data.message,
            confirmButtonText: '确认',
            confirmButtonColor: '#00A7DC',
            customStyle: 'border-radius: 5px;',
            closeOnClickOverlay: true
          }).then(res => {

          })
        }
      })
    }
  },
  validForm() {
    if (!this.data.staffName) {
      this.showToast('请输入姓名')
      return false
    }
    // 202309整改： 去除身份证格式校验，改为使用账号登陆
    // if (!this.data.idNum || !(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(this.data.idNum))) {
    //   this.showToast('请输入正确的证件号码')
    //   return false
    // }
    if (!this.data.idNum) {
      this.showToast('请输入账号')
      return false
    }
    if (this.data.phoneNum.length!=11) {
      this.showToast('请输入正确的手机号码')
      return false
    }
    return true
  },
  showToast(str) {
    wx.showToast({
      title: str,
      icon: 'none'
    })
  }
})